package com.cloud.tio.tiocloud.server;

import com.alibaba.fastjson.JSON;
import com.cloud.tio.tiocloud.models.tio.TioData;
import com.cloud.tio.tiocloud.tio.common.packet.CloudPacket;
import org.tio.core.ChannelContext;
import org.tio.core.Tio;

import java.io.UnsupportedEncodingException;


public class TioServer {
    private final CloudPacket cloudPacket;
    private final ChannelContext channelContext;

    public TioServer(CloudPacket cloudPacket, ChannelContext channelContext) {
        this.cloudPacket = cloudPacket;
        this.channelContext = channelContext;
    }

    public void handler() throws UnsupportedEncodingException {
        byte[] body = cloudPacket.getBody();
        if (body != null) {
            String str = new String(body, CloudPacket.CHAR_SET);
            TioData tioData = JSON.parseObject(str, TioData.class);
            switch (tioData.getMsgType()) {
                case 0 -> {
                    //单聊信息
                    CloudPacket packet = new CloudPacket();
                    packet.setBody(body);
                    Tio.bSendToBsId(channelContext.tioConfig, tioData.getTo(), packet);
                }
                case 1 -> {
                    //群组消息
                    CloudPacket groupPacket = new CloudPacket();
                    groupPacket.setBody(body);
                    Tio.bSendToGroup(channelContext.tioConfig, tioData.getTo(), groupPacket);
                }
                case 2 ->
                    //绑定ID
                        Tio.bindBsId(channelContext, tioData.getFrom());
                case 3 -> {
                    //绑定群组
                    //1,根据uuid查找个人信息，群组，
                    //2，绑定群组
                }
            }
            System.out.println("收到消息来自客户端的消息：" + tioData.getBody());

//            CloudPacket resp = new CloudPacket();
//            resp.setBody(("服务端已经收到了你的消息，你的消息是:" + tioData.getBody()).getBytes(CloudPacket.CHAR_SET));
//            Tio.send(channelContext, resp);
        }
    }
}
